#!/usr/bin/env ruby
#
#  Created by Paul Gower on 2007-10-24.
#  Copyright (c) 2007. All rights reserved.

require "jumbalaya"
require 'test/unit'

# uses reflection to find tests, test methods must start with test
# the methods setup and teardown will be automatically run before/after each test method (they bracket the methods)


class JumbalayaTests < Test::Unit::TestCase
  
  teardown
  
  def db_type
    assert_raise(Jumbalaya::Exceptions::UnknownDatabaseType) { Jumbalaya::Database.new(:invalid) }
    assert_nothing_raised(Jumbalaya::Exceptions::UnknownDatabaseType) { Jumbalaya::Database.new(:sqlite3) }
  end
  
  def db_creation
    assert_not_nil( Jumbalaya::Database.new(:sqlite3) )
    assert_not_nil( Jumbalaya::Database.new(:sqlite3, :name => "jumbalaya.db") )
    assert_equal(Jumbalaya::Database, Jumbalaya::Database.new(:sqlite3).class)
    # assert_equal(SQLite3::Database, Jumbalaya::Database.new(:sqlite3).connection.class)
    # not really valid anymore because i subclassed SQLite3::Database in Jumbalaya::SQLite3Adaptor
    assert_equal(Jumbalaya::SQLite3Adaptor, Jumbalaya::Database.new(:sqlite3).connection.class)
    assert_raise(NoMethodError) { Jumbalaya::Database.new(:test_adaptor_type).execute("fake sql query") }
  end
  
  def db_operation
    assert_nothing_raised(SQLite3::SQLException) { Jumbalaya::Database.new(:sqlite3, :name => "jumbalaya.db").execute("select * from nonexistant") }
    assert_kind_of(Array, Jumbalaya::Database.new(:sqlite3, :name => "jumbalaya.db").execute("select * from boxes"))
  end
  
  def db_find
    class Circles < Jumbalaya::Core
    end
    c1 = Circles.find_by_name("circle_one")
    assert_kind_of(Jumbalaya::Core, c1)
    assert_equal("circle_one", c1.name)
    assert_equal(32, c1.radius)
  end
  
  def setup
    @tdb = SQLite3::Database.new("jumbalaya.db")
    @tdb.execute("CREATE TABLE boxes (id INTEGER PRIMARY KEY NOT NULL, name TEXT, width INTEGER, height INTEGER)")
    @tdb.execute("CREATE TABLE triangles (id INTEGER PRIMARY KEY NOT NULL, name TEXT, width INTEGER, height INTEGER)")
    @tdb.execute("CREATE TABLE circles (id INTEGER PRIMARY KEY NOT NULL, name TEXT, radius INTEGER)")
    @tdb.execute("INSERT INTO boxes VALUES (1, 'box_one', 30, 65)")
    @tdb.execute("INSERT INTO boxes VALUES (2, 'box_two', 25, 34)")
    @tdb.execute("INSERT INTO boxes VALUES (3, 'box_three', 89, 67)")
    @tdb.execute("INSERT INTO circles VALUES (1, 'circle_one', 32)")
    @tdb.execute("INSERT INTO circles VALUES (2, 'circle_two', 98)")
  end
  
  def teardown
    @tdb.execute("DROP TABLE boxes")
    @tdb.execute("DROP TABLE triangles")
    @tdb.execute("DROP TABLE circles")
  end
  
end

# TODO 
# check to make sure that calling a class method on a class without an adaptor tries and dies gracefully 
# check that if an alternative db name is passed that it is actually used
